import { getBaseUrl } from '@/services/urlconst';
import {
  getContractTempTabsSwitch,
  getContractUrgeSearchConfig,
  getMaterialSearchList,
  getSourceSearchList,
  getSubjectSearchList,
  getTempalSearchList,
  updateProjectQuery,
} from '../mconfig';
import { ManageCommonAPI } from '@/pages/type';
import { useRequest } from 'umi';
import { commonManageSearchParams, getLevelZero, getLoadMapList, getTenantID, getUserID, requestFunComponFiex, getLevelFirst } from '@/utils';
import { ILoadMapTypeAll, ISearchTranslateAll } from '@/common';
import { useMemo } from 'react';

const baseUrl = getBaseUrl();

/**
 * dataGrid 采购申请
 * @param curRes 权限
 * @returns
 */
const updateProcureoeDataGrid = (curRes: Record<string, any>) => {
  /**  需要获取的数据字典 */
  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`, //采购方式
    `${getTenantID()}${ILoadMapTypeAll.CURRYOUT_STATE}`, //状态
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`, //采购类别
  ];

  /** 获取数据字典loadMdicMap */
  const loadMdicMapObj: Record<string, any> = getLoadMapList(loadMdicIds);

  /** 获取权限参数 */
  // const queryObj: Record<string, any> = updateProjectQuery(curRes);

  /** 获取列表数据  */
  const { loading, run, refresh, tableProps, data, params } = useRequest(
    (opt: ManageCommonAPI.IGridRequestType) => {
      const requestBody: Record<string, any> = {
        current: 1,
        pageSize: 10,
        sort: 'createTime',
        order: 'desc',
        dicTypeIds: loadMdicIds?.toString(),
        state: `${getTenantID()}${ILoadMapTypeAll.CURRYOUT_STATE}1014`,
        // ...queryObj,
        ownDepartmentID: getLevelFirst(),
        params: 'ownDepartmentID',
        ...opt,
      };

      const requestURL = `${baseUrl}/contractController/purchaseSourceDataGrid/${requestBody?.params}`;
      return requestFunComponFiex('POST', requestURL, requestBody);
    },
    {
      manual: false, //页面初始请求为 true
      paginated: true,
      defaultPageSize: 10,
    },
  );

  /**  获取管理也数据  */
  const getManageData = (otherRequest: ManageCommonAPI.IGridRequestType | any) => {
    const request: ManageCommonAPI.IGridRequestType | any = {
      ...otherRequest,
    };

    if (request?.bidedTime) {
      const [bidedTimeStart, bidedTimeEnd] = request.bidedTime;
      request['bidedTimeStart'] = bidedTimeStart.format('YYYY-MM-DD 00:00:00');
      request['bidedTimeEnd'] = bidedTimeEnd.format('YYYY-MM-DD 23:59:59');
      delete request['bidedTime'];
    }
    run({ ...request });
  };

  /** 页面列表 */
  const returnTableProps = useMemo(() => {
    return {
      data,
      pagination: tableProps?.pagination,
      params: params?.[0],
    };
  }, [data, tableProps]);

  /** 搜索表单 */
  const searchList: any = getSourceSearchList(loadMdicMapObj?.loadMapInfo);

  return {
    getManageData,
    refreshManage: refresh,
    loading,
    searchList,
    ...returnTableProps,
  };
};

/**
 * dataGrid 合同范本
 * @param curRes 权限
 * @returns
 */
const updateTempDataGrid = (curRes: Record<string, any>, typeCode: string | any) => {
  /**  需要获取的数据字典 */
  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`, //合同类型
  ];

  /** 获取数据字典loadMdicMap */
  const loadMdicMapObj: Record<string, any> = getLoadMapList(loadMdicIds);

  /** 获取权限参数 */
  const queryObj: Record<string, any> = getContractTempTabsSwitch(curRes);

  /** 获取搜索参数 */
  const searchListParams = getTempalSearchList(loadMdicMapObj?.loadMapInfo, queryObj);

  /** 获取列表数据  */
  const { loading, run, refresh, tableProps, data, params } = useRequest(
    (opt: ManageCommonAPI.IGridRequestType) => {
      const requestBody: Record<string, any> = {
        current: 1,
        pageSize: 10,
        sort: 'createTime',
        order: 'desc',
        dicTypeIds: loadMdicIds?.toString(),
        ...queryObj,
        ...opt,
        state: `${getTenantID()}${ILoadMapTypeAll.CONTRACTTEMP_STATE}1002`,
        businessType: typeCode ? typeCode : null,
      };
      const searchParams: Record<string, any> = commonManageSearchParams(searchListParams, requestBody, {
        dicTransName: 'businessType',
        orgTransName: `${ISearchTranslateAll.SIGN_DEPT},${ISearchTranslateAll.CREATER_DEPT},${ISearchTranslateAll.OWNER_DEPT},${ISearchTranslateAll.CANCEL_DEPT}`,
        // areaTransName: `${ISearchTranslateAll.AREA_TRANS}`,
      });

      const requestURL = `${baseUrl}/contractTemplateController/dataGrid/${requestBody?.params}`;
      return requestFunComponFiex('POST', requestURL, searchParams);
    },
    {
      manual: false, //页面初始请求为 true
      paginated: true,
      defaultPageSize: 10,
    },
  );

  /**  获取管理也数据  */
  const getManageData = (otherRequest: ManageCommonAPI.IGridRequestType | any) => {
    const request: ManageCommonAPI.IGridRequestType | any = {
      ...otherRequest,
    };
    run({ ...request });
  };

  /** 页面列表 */
  const returnTableProps = useMemo(() => {
    return {
      data,
      pagination: tableProps?.pagination,
      params: params?.[0],
    };
  }, [data, tableProps]);

  return {
    getManageData,
    refreshManage: refresh,
    loading,
    searchList: searchListParams,
    ...returnTableProps,
  };
};

/**
 * dataGrid 合同主体
 * @param curRes 权限
 * @param serviceType true 为合同主体
 * @returns
 */
const openContractSubjectManage = (curRes: Record<string, any>, serviceType?: boolean) => {
  let creditList: string[] = ['12100000MB2001605R', '12110000MB1N5794X2'];

  /** 获取列表数据  */
  const { loading, run, refresh, tableProps, data, params } = useRequest(
    (opt: ManageCommonAPI.IGridRequestType) => {
      const requestBody: Record<string, any> = {
        current: 1,
        pageSize: 10,
        sort: 'createTime',
        order: 'desc',
        // dicTypeIds: loadMdicIds?.toString(),
        createCompanyID: getLevelZero(),
        params: 'createCompanyID',
        ...opt,
        creditID: creditList?.toString(),
        selectSign: serviceType,
      };

      const requestURL = `${baseUrl}/contractController/oppositeDataGrid/${requestBody?.params}`;
      return requestFunComponFiex('POST', requestURL, requestBody);
    },
    {
      manual: false, //页面初始请求为 true
      paginated: true,
      defaultPageSize: 10,
    },
  );

  /**  获取管理也数据  */
  const getManageData = (otherRequest: ManageCommonAPI.IGridRequestType | any) => {
    const request: ManageCommonAPI.IGridRequestType | any = {
      ...otherRequest,
    };
    run({ ...request });
  };

  /** 页面列表 */
  const returnTableProps = useMemo(() => {
    return {
      data,
      pagination: tableProps?.pagination,
      params: params?.[0],
    };
  }, [data, tableProps]);

  /** 搜索表单 */
  const searchList: any = getSubjectSearchList(serviceType ? true : false);

  return {
    getManageData,
    refreshManage: refresh,
    loading,
    searchList,
    dataList: data?.rows,
    ...returnTableProps,
  };
};

/**
 * 物料列表
 * @param curRes
 */
const materialTableService = (curRes: Record<string, any>) => {
  /**  需要获取的数据字典 */
  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`];

  /** 获取数据字典loadMdicMap */
  const loadMdicMapObj: Record<string, any> = getLoadMapList(loadMdicIds);

  /** 获取权限参数 */
  // const queryObj: Record<string, any> = materialSwitchTable(curRes);

  /** 获取列表数据  */
  const { loading, run, refresh, tableProps, data, params } = useRequest(
    (opt: ManageCommonAPI.IGridRequestType) => {
      const requestBody: Record<string, any> = {
        current: 1,
        pageSize: 10,
        dicTypeIds: loadMdicIds?.toString(),
        sort: 'createTime',
        order: 'desc',
        // ...queryObj,
        params: 'createCompanyID',
        createCompanyID: getLevelZero(),
        ...opt,
        // state: 2,
      };

      const requestURL = `${baseUrl}/contractController/materialDataGrid/${requestBody?.params}`;
      return requestFunComponFiex('POST', requestURL, requestBody);
    },
    {
      manual: true, //页面初始请求为 true
      paginated: true,
      defaultPageSize: 10,
    },
  );

  /**  获取管理也数据  */
  const getManageData = (otherRequest: ManageCommonAPI.IGridRequestType | any) => {
    const request: ManageCommonAPI.IGridRequestType | any = {
      ...otherRequest,
    };
    run({ ...request });
  };

  /** 搜索表单 */
  const searchList: any = getMaterialSearchList(loadMdicMapObj);

  /** 页面列表 */
  const returnTableProps = useMemo(() => {
    return {
      data,
      pagination: tableProps?.pagination,
      params: params?.[0],
    };
  }, [data, tableProps]);

  return {
    getManageData,
    refreshManage: refresh,
    loading,
    searchList,
    dataList: data?.rows,
    loadMdicMapObj,
    ...returnTableProps,
  };
};

/**
 * 查看督办记录列表
 * @param callback
 * @returns
 */
const handleUrgeDataGridService = (callback: (res: any) => void) => {
  const { run, loading, data } = useRequest(
    (payload: ManageCommonAPI.IGridRequestType) => {
      /**获取权限参数 */
      const queryTypeObj: Record<string, any> = {
        params: 'handlerID',
      };
      const searchListParams = getContractUrgeSearchConfig(queryTypeObj);

      const bodyParams: any = {
        ...payload,
        ...queryTypeObj,
        handleStyle: '0',
        current: 1,
        pageSize: 999,
        sort: 'handleTime',
        order: 'desc',
      };
      let reqUrl = `${baseUrl}/contractController/handleDataGrid/${bodyParams?.params}`;
      const searchParams: Record<string, any> = commonManageSearchParams(searchListParams, bodyParams, {
        orgTransName: `${ISearchTranslateAll.HAND_DEPT},${ISearchTranslateAll.OWNER_DEPT}`,
      });
      return requestFunComponFiex('POST', reqUrl, searchParams);
    },
    {
      manual: true, //页面初始请求为 true
      paginated: true,
      defaultPageSize: 999,
      onSuccess: callback,
    },
  );

  /**  获取管理也数据  */
  const getManageData = (otherRequest: ManageCommonAPI.IGridRequestType | any) => {
    const request: ManageCommonAPI.IGridRequestType | any = {
      ...otherRequest,
    };
    run({ ...request });
  };

  return {
    handleUrgeDataGridRun: getManageData,
    handleUrgeDataGridLoading: loading,
    handleUrgeData: data?.rows,
  };
};

export { updateProcureoeDataGrid, updateTempDataGrid, openContractSubjectManage, materialTableService, handleUrgeDataGridService };
